package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Description:
 * @author: Mr_Sun
 * @Date: 2018/9/2
 * @Time: 19:04
 */
@Service
public class BrandService {
    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> queryBrandByPage(Integer curren_page, Integer pageSize, String sortBy, Boolean desc, String key) {
        //分页
        PageHelper.startPage(curren_page, pageSize);
        Example example = new Example(Brand.class);
        //排序
        if (StringUtils.isNotBlank(sortBy)) {
            example.setOrderByClause(sortBy + (desc ? " DESC" : " ASC")); //DESC降序
        }
        if (StringUtils.isNotBlank(key)) {
            //查询
            example.createCriteria().orLike("name", "%"+key+"%").orEqualTo("letter", key.toUpperCase());
        }
        List<Brand> list = this.brandMapper.selectByExample(example);
        //创建pageInfo
        PageInfo<Brand> info = new PageInfo<>(list);
        PageResult<Brand> pageResult = new PageResult<>(info.getTotal(), info.getList());
        return pageResult;
    }
    /**
     * 新增商品分类和品牌中间表数据
     * @return
     */
    public void save(Brand brand, List<Long> ids) {
        //新增品牌
        this.brandMapper.insert(brand);
        //新增品牌和分类的中间表  前面插入成功  这里 brand.getId()就能够拿到id
        for (Long id : ids) {
            this.brandMapper.insertCategoryBrand(id,brand.getId());
        }

    }
    /**
     * 修改商品信息
     * @param brand
     * @param idss
     */
    public void updateBrand(Brand brand, List<Long> idss) {
//        brandMapper.up();
//        brandMapper.updateCategoryBrand();
        //1.修改brand表
        brandMapper.updateByPrimaryKey(brand);
        //2.修改中间表
        Object[] ids = idss.toArray();
        brandMapper.updateCategoryBrand(ids, brand.getId());


    }
    public int deleteBrandById(Long id) {
        int num= brandMapper.deleteBrandById(id);
        int numb = brandMapper.deleteMiddleById(id);
        return num+numb;
    }

    public List<Brand> queryBrandByCategory(Long cid) {
        List<Brand>  list= brandMapper.queryByCategoryId(cid);
        return list;
    }

    public Brand queryBrandByBid(Long bid) {
        Brand brand = brandMapper.selectByPrimaryKey(bid);
        return brand;
    }
}
